<?php

namespace modules\bluedashboard;

use Throwable;
use ba\Filesystem;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class Bluedashboard
{
    private string $uid = 'bluedashboard';

    /**
     * 更新
     * @throws Throwable
     */
    public function update(): void
    {
        // 兼容系统v1.1.2的语言包按需加载
        // 寻找安装时备份中的lang/pages文件，如果有，还原到lang/backend内而不是原位置
        $ebakDir = root_path() . 'modules' . DIRECTORY_SEPARATOR . 'ebak' . DIRECTORY_SEPARATOR;
        $zipFile = $ebakDir . $this->uid . '-install.zip';
        $zipDir  = false;
        if (is_file($zipFile)) {
            try {
                $zipDir = Filesystem::unzip($zipFile);
            } catch (Throwable) {
                // skip
            }
        }
        if ($zipDir) {
            $oldBaInputs = [
                Filesystem::fsFit('web\src\lang\pages\zh-cn\dashboard.ts'),
                Filesystem::fsFit('web\src\lang\pages\en\dashboard.ts')
            ];
            foreach ($oldBaInputs as $oldBaInput) {
                @unlink(root_path() . $oldBaInput);
            }

            foreach (
                $iterator = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($zipDir, FilesystemIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::SELF_FIRST
                ) as $item
            ) {
                $ebakFile = Filesystem::fsFit($iterator->getSubPathName());
                if (!$item->isDir() && in_array($ebakFile, $oldBaInputs)) {
                    $newFileName = str_replace(DIRECTORY_SEPARATOR . 'pages' . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR . 'backend' . DIRECTORY_SEPARATOR, $ebakFile);
                    copy($item, root_path() . $newFileName);
                }
            }
        }
        Filesystem::delDir($zipDir);
        Filesystem::delEmptyDir(root_path() . 'web/src/lang/pages/en');
        Filesystem::delEmptyDir(root_path() . 'web/src/lang/pages/zh-cn');
    }
}